package com.jiefutong.zyt;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.jiefutong.zyt.utils.BusProvider;
import com.jiefutong.zyt.utils.PrefsUtil;
import com.jiefutong.zyt.zxing.app.CaptureActivity;
import com.just.agentweb.AbsAgentWebSettings;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.IAgentWebSettings;
import com.just.agentweb.WebListenerManager;
import com.just.agentweb.download.DefaultDownloadImpl;
import com.just.agentweb.download.DownloadListenerAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.squareup.otto.Subscribe;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import gdut.bsx.share2.Share2;
import gdut.bsx.share2.ShareContentType;

import static com.umeng.socialize.utils.ContextUtil.getContext;

public class MainActivity extends AppCompatActivity {

    private RelativeLayout mRlContent;
    private AgentWeb mAgentWeb;
   // private String url = "https://zhangyitong.shanfuyg.com/mall/jiefutong/index.html?i=1";
    //  private String url = "http://demo.shanfuyg.com/demo";
    // private String url = "http://zhangyitongmall.shanfuyg.com/mall/jiefutong/index.html?i=1";
   private String url = "https://zyt.jiefutong.net/mall/jiefutong/index.html?i=1";
    private Context context;
    private String urls;
    private String tokens;
    private TextView mTvProgress;
    private View view;
    private String dirct = "";
    private String curUrl;
   // private ProgressBar mProgressBar;
   IWXAPI msgApi =null;
    //支付宝回调方法
    private String callbcakMethod="";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉标题栏
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        BusProvider.getInstance().register(this);
        context = this;
        urls = getIntent().getStringExtra("url");
        //tokens = getIntent().getStringExtra("token");
        tokens=PrefsUtil.getString(getApplicationContext(), "token","");
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏

        if (null == urls || TextUtils.isEmpty(urls)) {
            loadcode();
        }
        if (!TextUtils.isEmpty(urls) && urls.contains("mall/jiefutong")) {
            StatusBarUtil.setTranslucent(this);
        } else {
            StatusBarUtil.setColor(this, getResources().getColor(R.color.title_orange), 0);
        }

        initView();
    }

    public void loadUrl(String urls) {
        if (tokens != null && !TextUtils.isEmpty(tokens)) {
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(mRlContent, new RelativeLayout.LayoutParams(-1, -1))
                    .closeIndicator()
                    .additionalHttpHeader("Accept", "application/json")
                    .additionalHttpHeader("Authorization", tokens)

                    .setAgentWebWebSettings(getSettings())
                    .setWebChromeClient(mWebChromeClient)
                    .setMainFrameErrorView(R.layout.net_error, R.id.tv_refresh)
                    .setWebViewClient(mWebViewClient)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .interceptUnkownUrl()
                    .createAgentWeb()
                    .ready()
                    .go(urls);
        } else {
            mAgentWeb = AgentWeb.with(this)
                    .setAgentWebParent(mRlContent, new RelativeLayout.LayoutParams(-1, -1))
                    .closeIndicator()
                    .setAgentWebWebSettings(getSettings())
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .setMainFrameErrorView(R.layout.net_error, R.id.tv_refresh)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .interceptUnkownUrl()
                    .createAgentWeb()
                    .ready()
                    .go(urls);
        }

        String ua = mAgentWeb.getAgentWebSettings().getWebSettings().getUserAgentString();
        mAgentWeb.getAgentWebSettings().getWebSettings().setUserAgentString(ua+" JiefutongClient/"+ getVersionName());

        System.out.println("-----------:"+ua+" JiefutongClient "+ getVersionName());

        mAgentWeb.getJsInterfaceHolder().addJavaObject("Android", new AndroidInterface());
    }
    @Subscribe
    public void onOttoEvent(String data) {
        if (data.contains("wx")) {
            String[] str=data.split("-");
            if(str[1].equals("0")){
                String func = "javascript:"+callbcakMethod+"('"+1+"')";
                mAgentWeb.getUrlLoader().loadUrl(func);
            }else{
                String func = "javascript:"+callbcakMethod+"('"+0+"')";
                mAgentWeb.getUrlLoader().loadUrl(func);
            }


        }
    }

    /**
     * 获取版本号
     *
     * @return 版本号
     */
    public String getVersionName() {
        try {

            PackageManager pm = getContext().getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private void initView() {
        mRlContent = (RelativeLayout) findViewById(R.id.rl_content);
        view = findViewById(R.id.down);
        mTvProgress = (TextView) findViewById(R.id.tv_progress);
      //  mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        if (getIntent().getData() != null) {
            String qq = getIntent().getData().toString();
            loadUrl(qq);
        } else {
            if (null == urls || TextUtils.isEmpty(urls)) {
                loadUrl(url);
            } else {
                loadUrl(urls);
            }
        }
    }

    private void showpop(String content, final String url) {
        View view = View.inflate(context, R.layout.pop_version_up, null);
        TextView tvcontent = view.findViewById(R.id.tv_content);
        tvcontent.setText(content);
        ImageButton ibclose = view.findViewById(R.id.ib_close);
        final AlertDialog dialog = new AlertDialog.Builder(context, R.style.translucent_half)
                .setCancelable(false)
                .create();
        dialog.show();
        dialog.setContentView(view);
        view.findViewById(R.id.ib_level).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showupdate(url);
                dialog.dismiss();
            }
        });
        ibclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void loadcode() {
        OkGo.<String>post("https://zyt.jiefutong.net/update.php")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        final InfoBean bean = JSON.parseObject(response.body(), InfoBean.class);
                        if (bean != null && bean.code == 200) {
                            int code = getVersioncode();
                            System.out.println("-----------code:"+code+"--------"+bean.data.appcode);
                            if (code < bean.data.appcode) {
                                new AlertDialog.Builder(context)
                                        .setTitle("升级更新")
                                        .setMessage(bean.data.app_desc)
                                        .setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                startActivity(new Intent(context, MainActivity.class).putExtra("url", bean.data.app_url));
                                                dialog.dismiss();
                                            }
                                        })
                                        .setCancelable(false)
                                        .create()
                                        .show();
                                //showpop(bean.data.app_desc, bean.data.download_url);
                            }else{

                            }
                        }
                    }
                });
    }

    private void showupdate(final String url) {
        new PermissionUtil(context, PermissionUtil.PHOTO) {
            @Override
            public void onsuccess() {
                OkGo.<File>post(url)
                        .tag(this)
                        .execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                view.setVisibility(View.GONE);
                                install(response.body().getAbsolutePath());
                            }

                            @Override
                            public void downloadProgress(Progress progress) {
                                float mProgress = progress.fraction;
                                view.setVisibility(View.VISIBLE);
                                mTvProgress.setText(mProgress + " %");
                            }

                            @Override
                            public void onError(Response<File> response) {
                                super.onError(response);
                                view.setVisibility(View.GONE);
                                loadcode();
                                Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        };
    }

    /**
     * 获取版本号
     *
     * @return 版本号
     */
    public int getVersioncode() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    public String getVersionname() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "v1.0.0";
    }

    private String referer = "https://zyt.jiefutong.net";
   // private String jie = "zhangyitong.shanfuyg.com://";
   private String jie = "zyt.jiefutong.net://";
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            curUrl = url;
            if (url.startsWith("alipays")) {
                return true;
            }

            try {
                if (url.startsWith("wtloginmqq://ptlogin/qlogin")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
            } catch (Exception e) {
                Toast.makeText(context, "未安装QQ", Toast.LENGTH_SHORT).show();
                return true;
            }

            try {
                if (url.startsWith("weixin://dl/business")) {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivityForResult(intent, 100);
                    Toast.makeText(context, "暂不支持微信登录", Toast.LENGTH_SHORT).show();
                    return true;
                }
            } catch (Exception e) {
                Toast.makeText(context, "未安装微信", Toast.LENGTH_SHORT).show();
            }
            if (url.startsWith("weixin://wap/pay?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
            if (url.startsWith("https://wx.tenpay") || url.startsWith("http://wx.tenpay")) {
                Map<String, String> extraHeaders = new HashMap<String, String>();
                dirct = "&redirect_url=" + url.substring(url.indexOf(jie) + 27, url.length());
                extraHeaders.put("Referer", referer);
                extraHeaders.put("Accept", "application/json");
                extraHeaders.put("Authorization", tokens);
                view.loadUrl(url + dirct, extraHeaders);
                referer = url;
                return true;
            }
            if (tokens != null && !TextUtils.isEmpty(tokens)) {
                Map<String, String> heads = new HashMap<>();
                heads.put("Accept", "application/json");
                heads.put("Authorization", tokens);
                view.loadUrl(url, heads);
                return true;
            }
            if (url.startsWith("http://egou.leetx.net/user/getTPCCode")) {
                setResult(200);
                finish();
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Nullable
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            curUrl = request.getUrl().toString();
            if (request.getUrl().toString().startsWith("alipays")) {
                return true;
            }

            try {
                if (request.getUrl().toString().startsWith("wtloginmqq://ptlogin/qlogin")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
                    startActivity(intent);
                    return true;
                }
            } catch (Exception e) {
                Toast.makeText(context, "未安装QQ", Toast.LENGTH_SHORT).show();
                return true;
            }

            try {
                if (request.getUrl().toString().startsWith("weixin://dl/business")) {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
//                    startActivityForResult(intent, 100);
                    Toast.makeText(context, "暂不支持微信登录", Toast.LENGTH_SHORT).show();
                    return true;
                }
            } catch (Exception e) {
                Toast.makeText(context, "未安装微信", Toast.LENGTH_SHORT).show();
            }
            if (request.getUrl().toString().startsWith("weixin://wap/pay?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(request.getUrl().toString()));
                startActivity(intent);
                return true;
            }

            if (request.getUrl().toString().startsWith("https://wx.tenpay") || request.getUrl().toString().startsWith("http://wx.tenpay")) {
                Map<String, String> extraHeaders = new HashMap<String, String>();
                dirct = "&redirect_url=" + request.getUrl().toString().substring(request.getUrl().toString().indexOf(jie) + 27, request.getUrl().toString().length());
                extraHeaders.put("Referer", referer);
                extraHeaders.put("Accept", "application/json");
                extraHeaders.put("Authorization", tokens);
                view.loadUrl(request.getUrl().toString() + dirct, extraHeaders);
                referer = request.getUrl().toString();
                return true;
            }
            if (tokens != null && !TextUtils.isEmpty(tokens)) {
                Map<String, String> heads = new HashMap<>();
                heads.put("Accept", "application/json");
                heads.put("Authorization", tokens);
                view.loadUrl(request.getUrl().toString(), heads);
                return true;
            }
            if (request.getUrl().toString().startsWith("http://egou.leetx.net/user/getTPCCode")) {
                setResult(200);
                finish();
            }
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //mProgressBar.setVisibility(View.GONE);
            handler.proceed();
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            //mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //mProgressBar.setVisibility(View.GONE);
            String id = JPushInterface.getRegistrationID(MainActivity.this);
            mAgentWeb.getJsAccessEntrace().quickCallJs("getSaveRegId", id);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

    };
    private String method;
    private String plats;


    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (null != null || !TextUtils.isEmpty(urls)) {
            finish();
            return true;
        }
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        } else {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public class AndroidInterface {
        private static final int SDK_PAY_FLAG = 1;


        @SuppressLint("HandlerLeak")
        private Handler mHandler = new Handler() {
            @SuppressWarnings("unused")
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        @SuppressWarnings("unchecked")
                        PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                        /**
                         * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为9000则代表支付成功
                        if (TextUtils.equals(resultStatus, "9000")) {
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            //showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                            //Toast.makeText(getBaseContext(),""+payResult,Toast.LENGTH_SHORT).show();
                        } else {
                            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                            //  showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                            //Toast.makeText(getBaseContext(),""+payResult,Toast.LENGTH_SHORT).show();
                        }

                        String func = "javascript:"+callbcakMethod+"('"+resultStatus.trim()+"')";
                        mAgentWeb.getUrlLoader().loadUrl(func);
                        break;
                    }

                    default:
                        break;
                }
            };
        };


        @JavascriptInterface
        public void  Pay(final String orderInfo, String payType, String callMethod){
            System.out.println("-------------------payType:"+orderInfo);
            callbcakMethod=callMethod;

            if(payType.equals("ALIPAY")){
                alipay(orderInfo);
            }else if(payType.equals("WEIXIN")){
                wechartPay(orderInfo);
            }

        }


        @JavascriptInterface
        public void  getToken(String callbackName){
            String token= PrefsUtil.getString(getApplicationContext(), "token","");
            String func = "javascript:"+callbackName+"('"+token.trim()+"')";
            mAgentWeb.getUrlLoader().loadUrl(func);
        }



        //支付宝支付
        public void alipay(final String orderInfo) {
            //支付宝支付
            final Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(MainActivity.this);
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();

        }

        public void wechartPay(final String orderInfo){
            msgApi = WXAPIFactory.createWXAPI(context, null);
          //  IWXAPI api = null;
            Gson gson=new Gson();
            Map<String,String>   map = gson.fromJson(orderInfo,Map.class);

            String appId=map.get("appid");
            String partnerId=map.get("partnerid");
            String prepayId=map.get("prepayid");
            String nonceStr=map.get("noncestr");
            String timeStamp=map.get("timestamp");
            String packageValue=map.get("package");
            String sign=map.get("sign");

            msgApi.registerApp(appId);


            PayReq req = new PayReq();
            //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
            req.appId			= appId;
            req.partnerId		= partnerId;
            req.prepayId		= prepayId;
            req.nonceStr		= nonceStr;
            req.timeStamp		= timeStamp;
            req.packageValue	= packageValue;
            req.sign			= sign;
           // req.extData			= "app data"; // optional
           // Toast.makeText(MainActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            msgApi.sendReq(req);
            PrefsUtil.putString(MainActivity.this, "appId", appId);
        }

        @JavascriptInterface
        public void openCode() {
            new PermissionUtil(context, PermissionUtil.CAMERA) {
                @Override
                public void onsuccess() {
                    Intent intent = new Intent(context, CaptureActivity.class);
                    startActivityForResult(intent, 100);
                }
            };
        }

        @JavascriptInterface
        public void sendToken(String token) {
            tokens = token;
        }


        @JavascriptInterface
        public void exitLogin() {
            PrefsUtil.putString(MainActivity.this, "token", null);
            Intent intent=new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
            finish();
        }



        @JavascriptInterface
        public void finish() {
            finish();
        }

        @JavascriptInterface
        public void saveImg(final String pic) {
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    savetoPhoto(pic);
                }
            };
        }

        @JavascriptInterface
        public void sharePlatform(final String pic) {
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    showdialog(pic);
                }
            };
        }

        @JavascriptInterface
        public void GetGPS(String methods) {
            method = methods;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (isLocationEnabled()) {
                        getlocation();
                    } else {
                        openGPS();
                    }
                }
            });

        }

        @JavascriptInterface
        public void SetHeadBar(String type, String text, String color, String h) {
            if (type.equals("0")) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StatusBarUtil.hideFakeStatusBarView(MainActivity.this);
                    }
                });
            }
            StatusBarUtil.setColor(MainActivity.this, Color.parseColor(color));
            if (!text.contains("ff")) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//黑色
            } else {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//白色
            }
        }

        @JavascriptInterface
        public void SingleShare(final String title, final String desc, final String url, final String link, final String plat, String meh) {
            method = meh;
            plats = plat;
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    if (plat.contains("Wechat")) {
                        new Share2.Builder(MainActivity.this)
                                .setContentType(ShareContentType.TEXT)
                                .setShareToComponent("com.tencent.mm", "")
                                .setOnActivityResult(400)
                                .setTitle(title)
                                .setTextContent(link)
                                .setShareFileUri(Uri.parse(url))
                                .build()
                                .shareBySystem();
                    } else if (plat.contains("Q")) {
                        new Share2.Builder(MainActivity.this)
                                .setContentType(ShareContentType.TEXT)
                                .setShareToComponent("com.tencent.mobileqq", "")
                                .setOnActivityResult(400)
                                .setTitle(title)
                                .setTextContent(link)
                                .setShareFileUri(Uri.parse(url))
                                .build()
                                .shareBySystem();
                    } else if (plat.contains("Sina")) {
                        new Share2.Builder(MainActivity.this)
                                .setContentType(ShareContentType.TEXT)
                                .setShareToComponent("com.sina.weibo", "")
                                .setOnActivityResult(400)
                                .setTitle(title)
                                .setTextContent(link)
                                .setShareFileUri(Uri.parse(url))
                                .build()
                                .shareBySystem();
                    }
                }
            };
//            if (plat.contains("Wechat")) {
//                if (!QQWXUtils.isAppAvilible(context, "com.tencent.mm")) {
//                    Toast.makeText(MainActivity.this, "您还没有安装微信", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Intent imageIntent = new Intent(Intent.ACTION_SEND);
//                imageIntent.setPackage("com.tencent.mm");
//                imageIntent.setType("text/plain");
//                imageIntent.putExtra(Intent.EXTRA_SUBJECT, link);
//                imageIntent.putExtra(Intent.EXTRA_TEXT, desc);
//                imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//                startActivity(Intent.createChooser(imageIntent, title));
//            }
//
//            if (plat.contains("Q")) {
//                if (!QQWXUtils.isAppAvilible(context, "com.tencent.mobileqq")) {
//                    Toast.makeText(MainActivity.this, "您还没有安装QQ", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Intent imageIntent = new Intent(Intent.ACTION_SEND);
//                imageIntent.setPackage("com.tencent.mobileqq");
//                imageIntent.setType("text/plain");
//                imageIntent.putExtra(Intent.EXTRA_SUBJECT, link);
//                imageIntent.putExtra(Intent.EXTRA_TEXT, desc);
//                imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//                startActivity(Intent.createChooser(imageIntent, title));
//            }
//
//            if (plat.contains("Sina")) {
//                if (!QQWXUtils.isAppAvilible(context, "com.sina.weibo")) {
//                    Toast.makeText(MainActivity.this, "您还没有安装微博", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Intent imageIntent = new Intent(Intent.ACTION_SEND);
//                imageIntent.setPackage("com.sina.weibo");
//                imageIntent.setType("text/plain");
//                imageIntent.putExtra(Intent.EXTRA_SUBJECT, link);
//                imageIntent.putExtra(Intent.EXTRA_TEXT, desc);
//                imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//                startActivity(Intent.createChooser(imageIntent, title));
//            }
//            JSONObject object = new JSONObject();
//            object.put("platform", plat);
//            object.put("state", "success");
//            mAgentWeb.getJsAccessEntrace().quickCallJs(method, object.toString());
        }

        @JavascriptInterface
        public void SingleShareImg(final String url, final String plat, String meh) {
            method = meh;
            plats = plat;
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    if (plat.contains("Wechat")) {
                        new Share2.Builder(MainActivity.this)
                                .setContentType(ShareContentType.IMAGE)
                                .setShareFileUri(Uri.parse(url))
                                .setShareToComponent("com.tencent.mm", "")
                                .setOnActivityResult(400)
                                .build()
                                .shareBySystem();
                    } else if (plat.contains("Q")) {
                        new Share2.Builder(MainActivity.this)
                                .setContentType(ShareContentType.IMAGE)
                                .setShareFileUri(Uri.parse(url))
                                .setShareToComponent("com.tencent.mobileqq", "")
                                .setOnActivityResult(400)
                                .build()
                                .shareBySystem();
                    } else if (plat.contains("Sina")) {
                        new Share2.Builder(MainActivity.this)
                                .setContentType(ShareContentType.IMAGE)
                                .setShareFileUri(Uri.parse(url))
                                .setShareToComponent("com.sina.weibo", "")
                                .setOnActivityResult(400)
                                .build()
                                .shareBySystem();
                    }
                }
            };
//            if (plat.contains("Wechat")) {
//                if (!QQWXUtils.isAppAvilible(context, "com.tencent.mm")) {
//                    Toast.makeText(MainActivity.this, "您还没有安装微信", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Intent imageIntent = new Intent(Intent.ACTION_SEND);
//                imageIntent.setPackage("com.tencent.mm");
//                imageIntent.setType("image/*");
//                imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//                startActivity(Intent.createChooser(imageIntent, "分享"));
//            }
//
//            if (plat.contains("Q")) {
//                if (!QQWXUtils.isAppAvilible(context, "com.tencent.mobileqq")) {
//                    Toast.makeText(MainActivity.this, "您还没有安装QQ", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Intent imageIntent = new Intent(Intent.ACTION_SEND);
//                imageIntent.setPackage("com.tencent.mobileqq");
//                imageIntent.setType("image/*");
//                imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//                startActivity(Intent.createChooser(imageIntent, "分享"));
//            }
//
//            if (plat.contains("Sina")) {
//                if (!QQWXUtils.isAppAvilible(context, "com.sina.weibo")) {
//                    Toast.makeText(MainActivity.this, "您还没有安装微博", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Intent imageIntent = new Intent(Intent.ACTION_SEND);
//                imageIntent.setPackage("com.sina.weibo");
//                imageIntent.setType("image/*");
//                imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//                startActivity(Intent.createChooser(imageIntent, "分享"));
//            }
//            JSONObject object = new JSONObject();
//            object.put("platform", plat);
//            object.put("state", "success");
//            mAgentWeb.getJsAccessEntrace().quickCallJs(method, object.toString());

        }

        @JavascriptInterface
        public void ShareImg(final String url, String meh) {
            method = meh;
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    new Share2.Builder(MainActivity.this)
                            .setContentType(ShareContentType.IMAGE)
                            .setShareFileUri(Uri.parse(url))
                            .setOnActivityResult(400)
                            .build()
                            .shareBySystem();
                }
            };

//            Intent imageIntent = new Intent(Intent.ACTION_SEND);
//            imageIntent.setType("image/*");
//            imageIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
//            startActivity(Intent.createChooser(imageIntent, "分享"));
//            JSONObject object = new JSONObject();
//            object.put("platform", "");
//            object.put("state", "success");
//            mAgentWeb.getJsAccessEntrace().quickCallJs(method, object.toString());
        }

        @JavascriptInterface
        public void Share(final String title, final String desc, final String url, final String link, String meh) {
            method = meh;
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    new Share2.Builder(MainActivity.this)
                            .setContentType(ShareContentType.TEXT)
                            .setShareFileUri(Uri.parse(url))
                            .setOnActivityResult(400)
                            .setTitle(title)
                            .setTextContent(link)
                            .build()
                            .shareBySystem();
                }
            };
        }

        @JavascriptInterface
        public void CopyText(final String text) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText(null, text);
                    clipboard.setPrimaryClip(clipData);
                    Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @JavascriptInterface
        public void CopyUrl() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (curUrl != null && !TextUtils.isEmpty(curUrl)) {
                        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clipData = ClipData.newPlainText(null, curUrl);
                        clipboard.setPrimaryClip(clipData);
                        Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

        @JavascriptInterface
        public void OpenByBrowser(String type, String url) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

        @JavascriptInterface
        public void GetClipboard(String meth) {
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData data = clipboard.getPrimaryClip();
            try {
                ClipData.Item item = data.getItemAt(0);
                String content = item.getText().toString();
                mAgentWeb.getJsAccessEntrace().quickCallJs(method, content);
            } catch (Exception e) {

            }
        }

        @JavascriptInterface
        public void GetScan(final String meth) {
            new PermissionUtil(context, PermissionUtil.CAMERA) {
                @Override
                public void onsuccess() {
                    method = meth;
                    scan = true;
                    Intent intent = new Intent(context, CaptureActivity.class);
                    startActivityForResult(intent, 100);
                }
            };
        }

        @JavascriptInterface
        public void Scan() {
            new PermissionUtil(context, PermissionUtil.CAMERA) {
                @Override
                public void onsuccess() {
                    Intent intent = new Intent(context, CaptureActivity.class);
                    startActivity(intent);
                }
            };
        }

        @JavascriptInterface
        public void Qcode(String type, final String meth) {
            new PermissionUtil(context, PermissionUtil.CAMERA) {
                @Override
                public void onsuccess() {
                    method = meth;
                    scan = true;
                    Intent intent = new Intent(context, CaptureActivity.class);
                    startActivityForResult(intent, 100);
                }
            };
        }

        @JavascriptInterface
        public void QrPhoto(String type, final String meth) {
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    method = meth;
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 200);
                }
            };
        }

        @JavascriptInterface
        public void QrUrl(String type, final String url, final String meth) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                   /* XQRCode.analyzeQRCode(url, new QRCodeAnalyzeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap bitmap, String result) {
                            mAgentWeb.getJsAccessEntrace().quickCallJs(meth, result);
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            Toast.makeText(context, "解析失败", Toast.LENGTH_SHORT).show();
                        }
                    });*/
                }
            });
        }

        @JavascriptInterface
        public void CCache() {
            mAgentWeb.clearWebCache();
        }

        @JavascriptInterface
        public void GetVersion(String meth) {
            mAgentWeb.getJsAccessEntrace().quickCallJs(meth, getVersionname());
        }

        @JavascriptInterface
        public void CheckFirstInstall(String meth) {
            int times = PreferencesUtils.getInt(MainActivity.this, Constant.FIRST, 0);
            if (times == 1) {
                mAgentWeb.getJsAccessEntrace().quickCallJs(meth, "true");
            } else {
                mAgentWeb.getJsAccessEntrace().quickCallJs(meth, "false");
            }
        }

        @JavascriptInterface
        public void Screenshot(final boolean start, final String meth) {
            new PermissionUtil(context, PermissionUtil.PHOTO) {
                @Override
                public void onsuccess() {
                    final ScreenShotListenManager manager = ScreenShotListenManager.newInstance(context);
                    manager.setListener(
                            new ScreenShotListenManager.OnScreenShotListener() {
                                public void onShot(String imagePath) {
                                    mAgentWeb.getJsAccessEntrace().quickCallJs(meth, imagePath);
                                }
                            }
                    );
                    if (start) {
                        manager.startListen();
                    } else {
                        manager.stopListen();
                    }
                }
            };
        }
    }

    private boolean scan;
    private AlertDialog dialogs;

    private void openGPS() {
        if (dialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("提示");
            builder.setMessage("您未开启位置信息,可能造成部分功能不可用，是否前往开启");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 0);
                    dialogs.dismiss();
                }
            });
            builder.setCancelable(true);
            dialogs = builder.create();
            dialogs.show();
        } else {
            dialogs.show();
        }
    }

    private void savetoPhoto(String pic) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "image";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Bitmap bitmap = returnBitMap(pic);
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Bitmap bitmap;

    public Bitmap returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 0) {
            getlocation();
        }

        if (requestCode == 400) {
            JSONObject object = new JSONObject();
            if (plats != null && !TextUtils.isEmpty(plats)) {
                object.put("platform", plats);
            } else {
                object.put("platform", "");
            }
            object.put("state", "success");
            mAgentWeb.getJsAccessEntrace().quickCallJs(method, object.toString());
        }


    }

    private void getlocation() {
        new PermissionUtil(context, PermissionUtil.LOCATION) {
            @SuppressLint("MissingPermission")
            @Override
            public void onsuccess() {
                LocationManager lManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                String bestProvider = lManager.getBestProvider(getCriteria(), true);
                Location location = lManager.getLastKnownLocation(bestProvider);
                JSONObject object = new JSONObject();
                object.put("latitude", String.valueOf(location.getLatitude()));
                object.put("longitude", String.valueOf(location.getLongitude()));
                mAgentWeb.getJsAccessEntrace().quickCallJs(method, object.toString());
            }
        };
    }


    public class ShareListener implements UMShareListener {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {

        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            if (throwable.getMessage().contains("2008")) {
                Toast.makeText(context, "没有安装应用", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {

        }
    }

    private DownloadListenerAdapter adapter = new DownloadListenerAdapter() {
        @Override
        public boolean onResult(String path, String url, Throwable throwable) {
            view.setVisibility(View.GONE);
            if (null == throwable) {
                //showToast("下载成功");
            } else {
                if (null == throwable) {
                    Toast.makeText(context, "下载失败,请重试", Toast.LENGTH_SHORT).show();
                } else {
                    install(path);
                }
            }
            return false;
        }

        @Override
        public void onProgress(String url, long downloaded, long length, long usedTime) {
            super.onProgress(url, downloaded, length, usedTime);
            int mProgress = (int) ((downloaded) / Float.valueOf(length) * 100);
            view.setVisibility(View.VISIBLE);
            mTvProgress.setText(mProgress + " %");
        }
    };

    /**
     * @return IAgentWebSettings
     */
    public IAgentWebSettings getSettings() {
        return new AbsAgentWebSettings() {
            private AgentWeb mAgentWeb;

            @Override
            protected void bindAgentWebSupport(AgentWeb agentWeb) {
                this.mAgentWeb = agentWeb;
            }

            /**
             * 如果你需要监听下载结果，请自定义 AgentWebSetting ， New 出 DefaultDownloadImpl，传入DownloadListenerAdapter
             * 实现进度或者结果监听，例如下面这个例子，如果你不需要监听进度，或者下载结果，下面 setDownloader 的例子可以忽略。
             * @param webView
             * @param downloadListener
             * @return WebListenerManager
             */
            @Override
            public WebListenerManager setDownloader(WebView webView, DownloadListener downloadListener) {
                return super.setDownloader(webView,
                        DefaultDownloadImpl
                                .create((Activity) webView.getContext(),
                                        webView,
                                        adapter,
                                        adapter,
                                        this.mAgentWeb.getPermissionInterceptor()));
            }
        };
    }

    private Dialog dialog;

    private void showdialog(final String url) {
        if (dialog == null) {
            dialog = new Dialog(context, R.style.ActionSheetDialogStyle);
            View inflate = View.inflate(context, R.layout.layout_share_pic, null);
            inflate.findViewById(R.id.inCome_wxLL).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    share(0, url);
                }
            });
//            inflate.findViewById(R.id.inCome_wxFriendLL).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    share(1, url);
//                }
//            });
            inflate.findViewById(R.id.inCome_qqLL).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    share(2, url);
                }
            });
//            inflate.findViewById(R.id.inCome_qqZoneLL).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    share(3, url);
//
//                }
//            });
            inflate.findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setContentView(inflate);
            dialog.setCanceledOnTouchOutside(true);

            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialog.show();
            WindowManager windowManager = this.getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            WindowManager.LayoutParams lp2 = dialog.getWindow().getAttributes();
            lp2.width = (int) (display.getWidth()); //设置宽度
            dialog.getWindow().setAttributes(lp2);
        } else {
            dialog.show();
        }
    }

    private void share(int i, String url) {
        if (i == 0 || i == 1) {
            if (!QQWXUtils.isAppAvilible(context, "com.tencent.mm")) {
                Toast.makeText(this, "您还没有安装微信", Toast.LENGTH_SHORT).show();
                return;
            } else {
                dealshare(i, url);
            }
        } else {
            if (!QQWXUtils.isAppAvilible(context, "com.tencent.mobileqq")) {
                Toast.makeText(this, "您还没有安装QQ", Toast.LENGTH_SHORT).show();
                return;
            } else {
                dealshare(i, url);
            }
        }
        dialog.dismiss();
    }

    private void dealshare(final int i, final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Intent intent = new Intent();
                    if (i == 0) {
                        intent.setPackage("com.tencent.mm");
                        intent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
                    }
//                    else if (i == 1) {
//                        intent.setPackage("com.tencent.mm");
//                        intent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
//                    }
                    else {
                        intent.setPackage("com.tencent.mobileqq");
                        intent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
                    }
//                    } else {
//                        intent.setPackage("com.tencent.mobileqq");
//                        intent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
//                    }
                    intent.setAction(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_TEXT, url);
                    intent.putExtra("Kdescription", "分享到");
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    private static Criteria getCriteria() {
        Criteria criteria = new Criteria();
        // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        // 设置是否需要方位信息
        criteria.setBearingRequired(false);
        // 设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }

    private void install(String filePath) {
        try {
            File apkFile = new File(filePath);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(
                        context
                        , Constant.FILE_PATH
                        , apkFile);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            }
            startActivity(intent);
            finish();
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "安装失败,请重试", Toast.LENGTH_SHORT).show();
        }
    }

}
